<?php

abstract class Phptal_Controller extends Doctrine_Controller
{
	public function __construct()
	{
		parent::__construct();	
		$this->view = new Phptal();

		$this->errors = array();
		$this->messages = array();
	}

	protected function render( $template = null )
	{
		if ( empty( $template ) )
		{
			$layout = Kohana::config('phptal.layout');
			$path = array_merge( array_slice(Router::$rsegments, 0, -1), array($layout) );
			$template = $this->get_template( implode( '/', $path ) );
			if ( ! $template )
				$template = $this->get_template( Router::$routed_uri );
		}
		else
			$template = $this->get_template( $template );

		if ( ! $template )
			throw new Exception( 'View template not found' );

		$this->view->errors = $this->errors;
		$this->view->messages = $this->messages;
		$this->view->method = Router::$method;
		$this->view->controller = Router::$controller;

		$this->view->setTemplate( $template );
		echo $this->view->execute();
	}

	private function get_template( $template )
	{
		return Kohana::find_file( 'views', $template, false, Kohana::config('phptal.extension') );
	}
}
